package cn.edu.niit.studyspace.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import org.litepal.crud.DataSupport;

import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.bean.Note;

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {

  private Context context;
  private List<Note> notes;

  public NoteAdapter(Context context, List<Note> notes) {
    this.context = context;
    this.notes = notes;
  }

  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note, parent, false);
    return new ViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    Note note = notes.get(position);
    viewHolder.title.setText(note.getTitle());
    viewHolder.content.setText(note.getContent());
    viewHolder.num.setText(position + 1 + "");
    viewHolder.date.setText(note.getDate());
    viewHolder.itemView.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {

            AlertDialog alertDialog =
                new AlertDialog.Builder(context)
                    .setTitle("删除")
                    .setMessage("是否删除该条笔记?")
                    .setNegativeButton(
                        "是",
                        new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialog, int which) {
                            DataSupport.delete(Note.class, note.getId());
                            getAllNotes();
                          }
                        })
                    .setPositiveButton("否", null)
                    .create();
            alertDialog.show();

            return false;
          }
        });
  }

  @Override
  public int getItemCount() {
    System.out.println("hello world \n");
    return notes.size();

  }

  public void notifyData(List<Note> notes) {
    this.notes = notes;
    notifyDataSetChanged();
  }

  private void getAllNotes() {
    notes = DataSupport.findAll(Note.class);
    notifyData(notes);
  }

  static class ViewHolder extends RecyclerView.ViewHolder {
    TextView num;
    TextView title;
    TextView date;
    TextView content;

    public ViewHolder(@NonNull View itemView) {
      super(itemView);
      num = itemView.findViewById(R.id.tv_num);
      title = itemView.findViewById(R.id.tv_title);
      content = itemView.findViewById(R.id.tv_content);
      date = itemView.findViewById(R.id.tv_date);
    }
  }
}
